﻿namespace YnabCsvConverter.Core.Converters
{
   using System.Collections.Generic;
   using System.Globalization;
   using System.IO;
   using System.Linq;
   using System.Text;
   using CsvHelper;
   using CsvHelper.Configuration;

   /// <summary>
   /// Simple Csv Converter
   /// </summary>
   [ConverterName("Generic simple csv | Date, Text, Amount")]
   public class SimpleCsvConverter : BaseConverter, IConverter
   {
      /// <summary>
      /// Initializes a new instance of the <see cref="SimpleCsvConverter" /> class.
      /// </summary>
      public SimpleCsvConverter()
      {
         SourceCulture = CultureInfo.InvariantCulture;
      }

      /// <summary>
      /// Converts this instance.
      /// </summary>
      /// <param name="sourceFilename">The source filename.</param>
      /// <param name="targetFilename">The target filename.</param>
      /// <param name="mode">The creation mode.</param>
      /// <returns>
      /// The Converter Result.
      /// </returns>
      public ConverterResult Convert(string sourceFilename, string targetFilename, CreationMode mode)
      {
         // Read specific records from source file.
         IEnumerable<SimpleCsvRecord> simpleRecords = ReadRecords<SimpleCsvRecord>(sourceFilename, ',', false);

         // Convert records from source file to YNAB records.
         IEnumerable<YnabRecord> ynabRecords = ConvertRecords(simpleRecords);

         // Write YNAB records to target file.
         WriteRecords(ynabRecords, targetFilename, mode);

         // Return a result
         return new ConverterResult {IsSuccess = true};
      }

      /// <summary>
      /// Converts to ynab lines.
      /// </summary>
      /// <param name="simpleRecords">The simple csv records.</param>
      /// <returns></returns>
      /// <exception cref="System.NotImplementedException"></exception>
      public IEnumerable<YnabRecord> ConvertRecords(IEnumerable<SimpleCsvRecord> simpleRecords)
      {
         return simpleRecords.Select(ConvertRecord).ToList();
      }

      /// <summary>
      /// Converts to ynab CSV line.
      /// </summary>
      /// <param name="simpleRecord">The simple csv record.</param>
      /// <returns></returns>
      /// <exception cref="System.NotImplementedException"></exception>
      public YnabRecord ConvertRecord(SimpleCsvRecord simpleRecord)
      {
         var ynabRecord = new YnabRecord();

         ynabRecord.SetDate(simpleRecord.Date, SourceCulture);
         ynabRecord.SetInflowOutflow(simpleRecord.Amount, SourceCulture);

         ynabRecord.Payee = simpleRecord.Text;
         ynabRecord.Memo = string.Empty;
         ynabRecord.Category = string.Empty;

         return ynabRecord;
      }
   }
}